import {defineStore} from "pinia";
import {simpleGet} from "@/utils/request";
import router from "@/router";
import {useLayoutSetStore} from "@/store/layout-set";

interface Admin {
    info: any,
    rules: Array<string>,
    system: object,
    menus:Array<object>,
    site: any,
}

export const useAdminStore = defineStore('admin', {
    state: () : Admin => ({
        info: {},
        rules:[],
        system:{},
        menus: [],
        site:{},
    }),
    actions:{
        async init(){
            const res = await simpleGet('/index/init')

            const {admin, rules, menus, system, site} = res

            this.info = admin
            this.rules = rules
            this.menus = menus
            this.system = system
            this.site = site
            // 添加路由
            let routes = _makeRoutes(menus)

            // 修改title
            document.title = site.title
            const layoutStore = useLayoutSetStore()
            layoutStore.title = site.title

            for (let route of routes){
                router.addRoute("layout", route)
            }

        }
    }
})


// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../views/**/*.vue')

const _makeRoutes = (menus:any[]) => {

    let routes: any[] = []
    for (let i = 0; i < menus.length; i++){
        let item = menus[i]

        if (item.rule_type == 2){ // 只为菜单创建路由

            const routePath = item.route_path
            const viewPath = item.view_path ? item.view_path : item.route_path
            const routeName = item.route_name ? item.route_name : item.route_path
            let component =  modules[`../views${viewPath}.vue`]
            if (!component) component = modules[`../views/error/404.vue`]

            routes.push({
                path: routePath,
                name: routeName,
                meta: {
                    title: item.title,
                },
                component: component
            })
        }

        // 有下级菜单
        if (item.children && item.children.length>0){
            routes.push(..._makeRoutes(item.children))
        }

    }
    return routes
}
